package com.syni.mdd.yhd.common.all.service.impl.activity;

import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.dao.jpa.activity.BmsDrOrderLogDao;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.entity.activity.BmsDrLogic;
import com.syni.mdd.yhd.common.all.entity.activity.BmsDrOrderLog;
import com.syni.mdd.yhd.common.all.service.BmsBusinessService;
import com.syni.mdd.yhd.common.all.service.activity.BmsBackCardService;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrLogicService;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrOrderLogService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author hwq
 * @DATE 2019/9/23 10:34
 * @VERSION 1.0
 **/
@Service
public class BmsDrOrderLogServiceImpl extends BaseService<BmsDrOrderLog, Integer> implements BmsDrOrderLogService {


    @Autowired
    BmsDrOrderLogDao bmsDrOrderLogDao;

    @Autowired
    BmsDrLogicService bmsDrLogicService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsBackCardService bmsBackCardService;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public BmsDrOrderLogDao getBaseDao() {
        return bmsDrOrderLogDao;
    }

    public void countBackCard(BmsDxOrder bmsDxOrder, Integer groupBuyUseId, Double backMoney) {
        //判断活动开始,并且在活动内下单
        Integer timeStamp = DateTimeUtils.getNowTimeStamp();
        if(redisTemplate.hasKey(Constants.REDIS_KEY_FULL_BACK_CARD_OPEN)){
            String activityTime = redisTemplate.opsForValue().get(Constants.REDIS_KEY_FULL_BACK_CARD_OPEN).toString();
            String[] startEndTime = activityTime.split(",");
            Integer startTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[0],DateTimeUtils.DATE_PATTERN_DAY_07));
            Integer endTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(DateTimeUtils.converStringToDate(startEndTime[1],DateTimeUtils.DATE_PATTERN_DAY_07),1));
            Integer orderTime = DateTimeUtils.converDateToInterger(bmsDxOrder.getNewTime());
            List<BmsDrLogic> bmsDrLogicList = bmsDrLogicService.getUserTask(bmsDxOrder.getBmsUserId());
            boolean isCanRecordCard = false;
            if(bmsDrLogicList != null && bmsDrLogicList.size() > 0){
                BmsDrLogic bmsDrLogic = bmsDrLogicList.get(0);
                if(bmsDrLogic.getCompleteNum() < 5 && bmsDrLogic.getExpireTime() != null){
                    if(DateTimeUtils.converDateToInterger(bmsDrLogic.getExpireTime()) > timeStamp){
                        isCanRecordCard = true;
                    }
                }
            }
            if(orderTime >= startTime && orderTime < endTime || isCanRecordCard) {
                Integer userId = bmsDxOrder.getBmsUserId();
                Integer businessId = bmsDxOrder.getBmsBusinessId();
                Integer orderId = bmsDxOrder.getId();
                final int IS_HAVING_END = 5;
                Date nowTime = new Date();
                //查询该用户的完成次数
                Map<String,Object> conditionMap = new HashMap<>();
                conditionMap.put("userId",userId);
                List<BmsDrLogic> bmsDrLogics = bmsDrLogicService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                BmsDrLogic bmsDrLogic;
                if(!(bmsDrLogics != null && bmsDrLogics.size() > 0)){
                    bmsDrLogic = new BmsDrLogic();
                    bmsDrLogic.setUserId(userId);
                    bmsDrLogic.setStatus(Constants.COMMON_FLAG_FALSE_INT);
                    bmsDrLogic.setCompleteNum(1);
                    bmsDrLogic.setNewTime(nowTime);
                    bmsDrLogic.setExpireTime(DateTimeUtils.addDay(nowTime,15));
                    bmsDrLogicService.getBaseDao().save(bmsDrLogic);
                    recordUserOrder(businessId,userId,orderId,groupBuyUseId,backMoney,bmsDrLogic.getId());
                }else {
                    bmsDrLogic = bmsDrLogics.get(0);
                    //判断是否是第一单
                    if(bmsDrLogic.getCompleteNum() == 0){
                        bmsDrLogic.setExpireTime(DateTimeUtils.addDay(nowTime,15));
                    }
                    //任务没过期
                    if(DateTimeUtils.getNowTimeStamp() < DateTimeUtils.converDateToInterger(bmsDrLogic.getExpireTime())){
                        //判断是否达到+1的条件
                        if(bmsDrLogic.getStatus() == Constants.NOT_GET && bmsDrLogic.getCompleteNum() < IS_HAVING_END) {
                            List<BmsDrOrderLog> bmsDrOrderLogs = bmsDrOrderLogDao.findByDrLogicId(bmsDrLogic.getId());
                            Set<Integer> businessIds = bmsDrOrderLogs.stream().map(BmsDrOrderLog::getBuinessId).collect(Collectors.toSet());
                            if (!businessIds.contains(businessId)) {
                                bmsDrLogic.setCompleteNum(bmsDrLogic.getCompleteNum() + 1);
                                recordUserOrder(businessId, userId, orderId,groupBuyUseId,backMoney, bmsDrLogic.getId());
                                //判断是否达到5次
                                if (bmsDrLogic.getCompleteNum() == IS_HAVING_END) {
                                    bmsDrLogic.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                                    //提现操作
                                    bmsBackCardService.withdrawalHandle(userId,bmsDrLogic);
                                }
                                bmsDrLogicService.getBaseDao().save(bmsDrLogic);
                            }
                        }
                    }
                }
            }
        }
    }

    public void recordUserOrder(Integer businessId,Integer userId,Integer orderId,Integer groupBuyUseId,Double backMoney,Integer drLogicId){
        //记录当前订单的情况
        BmsDrOrderLog bmsDrOrderLog = new BmsDrOrderLog();
        bmsDrOrderLog.setBuinessId(businessId);
        bmsDrOrderLog.setUserId(userId);
        bmsDrOrderLog.setOrderId(orderId);
        bmsDrOrderLog.setGroupBuyUseId(groupBuyUseId);
        bmsDrOrderLog.setBackMoney(backMoney);
        bmsDrOrderLog.setNewTime(new Date());
        bmsDrOrderLog.setDrLogicId(drLogicId);
        Optional<BmsBusiness> bmsBusinessOptional = bmsBusinessService.getBaseDao().findById(businessId);
        if(bmsBusinessOptional.isPresent()){
            bmsDrOrderLog.setVendorName(bmsBusinessOptional.get().getVendorName());
        }
        bmsDrOrderLogDao.save(bmsDrOrderLog);
    }

    @Override
    public Double countTotalInDate(Date startTime, Date endTime) {
        Map<String,Object> conditionMap = new LinkedHashMap<>();
        conditionMap.put("newTime_GTTE",startTime);
        conditionMap.put("newTime_LTT",endTime);
        List<BmsDrOrderLog> bmsDrOrderLogs = bmsDrOrderLogDao.findAll(new SpecificationUtils(conditionMap));
        Double total = 0d;
        if(bmsDrOrderLogs != null && bmsDrOrderLogs.size() > 0){
            for(BmsDrOrderLog bmsDrOrderLog : bmsDrOrderLogs){
                total = ArithUtil.add(total,bmsDrOrderLog.getBackMoney());
            }
        }
        return total;
    }
}
